//
//  ZZComposeViewController.swift
//  sina
//
//  Created by 张鹏 on 16/5/30.
//  Copyright © 2016年 ZP. All rights reserved.
// 键盘的退出

import UIKit
import SnapKit
import SVProgressHUD

class ZZComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.yellowColor()
        setUpUI()
       //注册通知
        registerNotification()
    }
    
    //注册通知
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ZZComposeViewController.keyboardChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
    //键盘将要改变frame  toolBar需要做动画效果
    @objc private func keyboardChange(n: NSNotification) {
        print(n)
        //获取键盘显示或者隐藏的动画时间
        let time_t = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        //结构体能够直接存放在字典中?   --> 需要转换为 NSValue 才能存储
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        print(time_t,rect)
        //获取键盘的frame
        let offsetY = -screenHeight + rect.origin.y
        UIView.animateWithDuration(time_t) {
            //修改toolbar 应该修改约束 不能够直接修改frame
            self.toolBar.snp_updateConstraints(closure: { (make) in
                make.bottom.equalTo(offsetY)
            })
            //提前刷新页面
            self.view.layoutIfNeeded()
        }
    }

    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
  
    //设置UI
    func setUpUI() {
    
        setNav()
        setToolBar()
        setTextView()
    }
 
    //设置nav
    func setNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(ZZComposeViewController.close))
        
        navigationItem.rightBarButtonItem = rightBarbuttonItem
        // 右边按钮不可交互
        navigationItem.rightBarButtonItem?.enabled = false
        
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 220, height: 40))
        let titleLabel = UILabel(title: "发布微博", font: 16, textColor: UIColor.darkGrayColor())
        let nameLabel = UILabel(title: ZZUserAccountViewModel.sharedAccountViewModel.userAccount?.name ?? "", font: 13, textColor: UIColor.lightGrayColor())
        
        myView.addSubview(titleLabel)
        myView.addSubview(nameLabel)
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView.snp_centerX)
            make.top.equalTo(myView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(myView.snp_centerX)
            make.bottom.equalTo(myView.snp_bottom)
        }
        //赋值的操作
        navigationItem.titleView = myView
    }
    
    
    //设置文本输入视图
    private func setTextView() {
        self.view.addSubview(textView)
        //设置约束
        textView.snp_makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(64)
            //设置高度
            make.height.equalTo(screenHeight / 3)
            
        }

        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
    }
    
//    override func viewDidAppear(animated: Bool) {
//        super.viewDidAppear(animated)
//        
//        print("..................")
//        print(textView.frame)
//        
//    }
//    
    
    //设置底部工具栏
    func setToolBar() {
        self.view.addSubview(toolBar)
        //设置约束
        toolBar.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            //工具条有默认高度
        }
        
        var items = [UIBarButtonItem]()
        //操作数据 添加UIBarButtonItem
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
                            ["imageName": "compose_mentionbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_trendbutton_background","actionName": "selectPicture"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
                            ["imageName": "compose_add_background","actionName": "selectPicture"]]
        
        for item in itemSettings {
            let imageName = item["imageName"]
            let action = item["actionName"]!
            //添加自定义UIBarButtonItem
            let item  = UIBarButtonItem(imageName: imageName, title: nil, target: self, action: Selector(action))
            items.append(item)
            
            //添加弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        //给toolBar赋值
        toolBar.items = items
    }
    
    
    @objc private func close() {
    
        print("关闭")
    dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    //发布微博
    @objc private func send() {
        print("发送")
        ZZNetworkTools.sharedTools.sendStatus(textView.text) { (responseObject, error) in
            if error != nil {
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            //成功
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
        }
    }
    
    //设置selectPicture的点击方法
    @objc private func selectPicture() {
    
        print("发布图片")
        //设置ZZComposePictureSelectorController的约束
        pictureSelector.view.snp_updateConstraints { (make) in
            
            make.height.equalTo(screenHeight/3 * 2)
        }
        
        
    }
    //设置selectEmoticon的点击方法
    @objc private func selectEmoticon() {
        
        print("发布表情")
    }
    
    //懒加载
    //底部工具栏
    private lazy var toolBar : UIToolbar = UIToolbar()
    
    //文本输入
    private lazy var textView: UITextView = {
        let tv = UITextView()
        //tv.text = "因何而生,因何而战"
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        //设置滚动视图键盘消失的方式
        tv.keyboardDismissMode = .OnDrag
        tv.alwaysBounceVertical = true
        tv.delegate = self
        return tv
    }()
    
    
    //右边按钮
    private lazy var rightBarbuttonItem: UIBarButtonItem = {
        let btn = UIButton()
        //设置文案
        btn.setTitle("发送", forState: .Normal)
        //添加点击事件
        btn.addTarget(self, action:#selector(ZZComposeViewController.send) , forControlEvents: .TouchUpInside)
        //设置根据内容显示
        //设置文字颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        let barButtonItem = UIBarButtonItem(customView: btn)
        
        return barButtonItem
    }()
    
     private lazy var placeHolderLabel: UILabel = UILabel(title: "", font: 18, textColor: UIColor.lightGrayColor())
 
    private lazy var pictureSelector : ZZComposePictureSelectorController = ZZComposePictureSelectorController()
    
}

//实现代理方法
extension ZZComposeViewController : UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        placeHolderLabel.hidden = textView.hasText()
        rightBarbuttonItem.enabled = textView.hasText()
    }
    
}

